import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/ad_banner/insert_ad.dart';
import 'package:pornhub_app/components/base_refresh/base_refresh_widget.dart';
import 'package:pornhub_app/components/blogger_cell/blogger_cell.dart';
import 'package:pornhub_app/components/image_view.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/components/text_view.dart';
import 'package:pornhub_app/generate/app_image_path.dart';
import 'package:pornhub_app/model/blogger_base_model.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/enum.dart';
import 'package:pornhub_app/utils/events.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/utils/initAdvertisementInfo.dart';

import '../controllers/blogger_list_page_controller.dart';

class BloggerListPageView extends StatefulWidget {
  final int loadType;
  final String province;
  final String city;
  const BloggerListPageView(
      {super.key,
      required this.loadType,
      required this.province,
      required this.city});

  @override
  State<BloggerListPageView> createState() => _BloggerListPageViewState();
}

class _BloggerListPageViewState extends State<BloggerListPageView> {
  late BloggerListPageController controller;
  AdPlaceEnum place = AdPlaceNameEnum.NDD_BANNER;

  StreamSubscription? subscription;
  StreamSubscription? locationEvent;
  StreamSubscription? clearLocationEvent;
  String tag = '';
  final ad = initWeightAdvertisementInfo(AdPlaceNameEnum.NDD_BANNER);

  RxString locationString = "".obs;
  List<String> municipalityItems = ["北京", "上海", "天津", "重庆"];
  List<String> specialZone = ["香港", "澳门"];

  @override
  void initState() {
    tag = "blogger_${widget.loadType}";

    // if (widget.province.isNotEmpty) {
    //   if (municipalityItems.contains(widget.province)) {
    //     locationString.value = "${widget.province}市";
    //   } else if (specialZone.contains(widget.province)) {
    //     locationString.value = "${widget.province}特区";
    //   } else {
    //     locationString.value = "${widget.province}省${widget.city}市";
    //   }
    // }

    controller = Get.put(
        BloggerListPageController(
            widget.loadType, widget.province, widget.city),
        tag: tag);
    subscription = eventBus.on<QueryEvent>().listen((event) {
      if (event.queryModel.loadType == widget.loadType) {
        controller.initQuery(event.queryModel);
      }
    });
    locationEvent = eventBus.on<LocationEvent>().listen((event) {
      if (event.loadType == widget.loadType) {
        if (municipalityItems.contains(event.provinces)) {
          locationString.value = "${event.cityName}市";
        } else if (specialZone.contains(event.provinces)) {
          locationString.value = "${event.provinces}特区";
        } else {
          locationString.value = "${event.provinces}省${event.cityName}市";
        }
        controller.queryModel.cityName = event.cityName;
        controller.initQuery(controller.queryModel);
      }
    });
    // clearLocationEvent = eventBus.on<ClearLocationEvent>().listen((event) {
    //   if (event.loadType != widget.loadType) {
    //     locationString.value = "";
    //     controller.queryModel.cityName =
    //         controller.userService.user.cityName ?? "";
    //     controller.initQuery(controller.queryModel);
    //   }
    // });
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      if (mounted) {
        // Future.delayed(Duration(milliseconds: 100), () {
        //   controller.refreshController
        //       .finishRefresh(IndicatorResult.success, true);
        // });
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BaseRefreshWidget(controller,
        child: GetBuilder<BloggerListPageController>(
            assignId: true,
            tag: tag,
            builder: (_) {
              return CustomScrollView(
                slivers: [
                  Container(
                    width: 372.w,
                    height: 32.w,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: COLOR.color_1D1D1D,
                      borderRadius: BorderRadius.circular(16.w),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ImageView(
                          src: AppImagePath.icons_search,
                          width: 13.w,
                          height: 13.w,
                        ),
                        9.horizontalSpace,
                        TextView(
                          text: "请输入搜索内容",
                          color: COLOR.color_898A8E,
                          fontSize: 12.w,
                        ),
                      ],
                    ),
                  ).marginBottom(16.w).onOpaqueTap(() {
                    Get.toNamed(Routes.search, arguments: "3");
                  }).sliver,
                  Obx(() => locationString.value.isEmpty
                      ? Container()
                      : Container(
                          width: 372.w,
                          height: 32.w,
                          padding: EdgeInsets.only(left: 14.w, right: 14.w),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: COLOR.color_1D1D1D,
                            borderRadius: BorderRadius.circular(14.w),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  ImageView(
                                    src: AppImagePath.arround_icon_location,
                                    width: 13.w,
                                    height: 16.w,
                                  ),
                                  9.horizontalSpace,
                                  TextView(
                                    text: "$locationString",
                                    color: COLOR.color_B93FFF,
                                    fontSize: 12.w,
                                  ),
                                ],
                              ),
                              ImageView(
                                src: AppImagePath.icons_close,
                                width: 13.w,
                                height: 13.w,
                              ),
                            ],
                          ),
                        ).marginBottom(18.w).onOpaqueTap(() {
                          locationString.value = "";
                          controller.queryModel.cityName =
                              controller.userService.user.cityName ?? "";
                          controller.initQuery(controller.queryModel);
                          eventBus
                              .fire(ClearLocationEvent(widget.loadType, ""));
                        })).sliver,
                  if (controller.isLoadedData == true &&
                      controller.totalCount == 0)
                    const NoData(
                      tips: "暂无符合条件的用户，调整下筛选项吧",
                    ).marginTop(44).sliver,
                  if (controller.totalCount > 0)
                    SliverPadding(
                      padding: EdgeInsets.only(left: 14.w, right: 14.w),
                      sliver: SliverList.builder(
                          itemCount: controller.totalCount,
                          itemBuilder: (context, index) {
                            List<BloggerBaseModel> models = controller
                                .bloggerItems
                                .skip(index * 12)
                                .take(12)
                                .toList();

                            return Column(
                              children: [
                                GridView.builder(
                                    padding: EdgeInsets.only(bottom: 6.w),
                                    shrinkWrap: true,
                                    itemCount: models.length,
                                    physics:
                                        const NeverScrollableScrollPhysics(),
                                    gridDelegate:
                                        SliverGridDelegateWithFixedCrossAxisCount(
                                            mainAxisSpacing: 6.w,
                                            crossAxisSpacing: 6.w,
                                            crossAxisCount: 3,
                                            childAspectRatio: 120 / 120),
                                    itemBuilder: (ctx, idx) {
                                      return BloggerCell(
                                        index: index * 12 + idx,
                                        model: models[idx],
                                      );
                                    }),
                                if (index == 0 && controller.totalCount > 1)
                                  Image.asset(
                                          AppImagePath.arround_ic_arround_vip)
                                      .marginOnly(
                                          bottom: ad != null ? 0.w : 6.w),
                                if (index != controller.totalCount - 1 &&
                                    ad != null)
                                  InsertAd(
                                    adress: AdPlaceNameEnum.NDD_BANNER,
                                    margin:
                                        EdgeInsets.only(top: 6.w, bottom: 6.w),
                                  )
                              ],
                            );
                          }),
                    )
                ],
              );
            }));
  }

  @override
  void dispose() {
    subscription?.cancel();
    locationEvent?.cancel();
    clearLocationEvent?.cancel();
    super.dispose();
  }
}
